package com.itany.util;

import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.concurrent.TimeUnit;

/**
 * Author：汤小洋
 * Date：2023-01-31 17:13
 * Description：分布式锁的工具类
 */
public class LockUtil {

    private static StringRedisTemplate redisTemplate = ApplicationContextHolder.getBean(StringRedisTemplate.class);

    // 锁的过期时间
    private static long lockTimeout = 10L;

    // 获取锁的超时时间
    private static long waitTimeout = 10000L;

    /**
     * 获取分布式锁
     */
    public static boolean getLock(String lockName,String value){
        // 计算获取锁的超时时间
        long endTime = System.currentTimeMillis() + waitTimeout;

        while(System.currentTimeMillis() < endTime){
            // 判断是否能够获取锁，其实就是往redis中存放数据
            Boolean flag = redisTemplate.opsForValue().setIfAbsent(lockName, value, lockTimeout, TimeUnit.SECONDS);
            if(flag){
                return true;
            }
        }

        return false;
    }

    /**
     * 释放锁
     */
    public static void unlock(String lockName,String value){
        if(redisTemplate.opsForValue().get(lockName).equals(value)){
            redisTemplate.delete(lockName);
        }
    }

}
